﻿<%@ WebHandler Language="C#" Class="imgup" %>


using System;
using System.Web;
using System.Text;
using System.IO;

public class imgup : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        if (context.Request["REQUEST_METHOD"] == "OPTIONS")
        {
            context.Response.End();
        }
        SaveFile();
    }

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string basePath = "/Up/")
    {

        string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
        basePath += _datePath;

        string serverPath = "~"+basePath;
        var name = string.Empty;
        serverPath = (serverPath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(serverPath) :
        serverPath;
        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;

        if (!Directory.Exists(serverPath))
            Directory.CreateDirectory(serverPath);

        var suffix = files[0].ContentType.Split('/');
        var _suffix = suffix[1];
        var _temp = System.Web.HttpContext.Current.Request["name"];

        //if (!string.IsNullOrEmpty(_temp))
        //{
        //    name = _temp;
        //}
        //else
        //{
        Random rand = new Random(24 * (int)DateTime.Now.Ticks);
        name = rand.Next() +"." +_suffix ;
        //}

        var full = serverPath + name;
        files[0].SaveAs(full);
        var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"" +basePath+name + "\"}";
        System.Web.HttpContext.Current.Response.Write(_result);
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}